package com.flyco.modules.fms.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.modules.pms.entity.PmsSkuStock;
import org.apache.shiro.SecurityUtils;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.fms.entity.FmsCategorySub;
import com.flyco.modules.fms.entity.FmsCategory;
import com.flyco.modules.fms.vo.FmsCategoryPage;
import com.flyco.modules.fms.service.IFmsCategoryService;
import com.flyco.modules.fms.service.IFmsCategorySubService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.flyco.common.aspect.annotation.AutoLog;

 /**
 * @Description: 科目大类
 * @Author: flyco
 * @Date:   2021-02-19
 * @Version: V1.0
 */
@Api(tags="科目大类")
@RestController
@RequestMapping("/f/fms/fmsCategory")
@Slf4j
public class FmsCategoryController {
	@Autowired
	private IFmsCategoryService fmsCategoryService;
	@Autowired
	private IFmsCategorySubService fmsCategorySubService;
	
	/**
	 * 分页列表查询
	 *
	 * @param fmsCategory
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "科目大类-分页列表查询")
    @ApiOperation(value="科目大类-分页列表查询", notes="科目大类-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(FmsCategory fmsCategory,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<FmsCategory> queryWrapper = QueryGenerator.initQueryWrapper(fmsCategory, req.getParameterMap());
		Page<FmsCategory> page = new Page<FmsCategory>(pageNo, pageSize);
		IPage<FmsCategory> pageList = fmsCategoryService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param fmsCategoryPage
	 * @return
	 */
	@AutoLog(value = "科目大类-添加")
	@ApiOperation(value="科目大类-添加", notes="科目大类-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody FmsCategoryPage fmsCategoryPage) {
       FmsCategory fmsCategory = new FmsCategory();
		BeanUtils.copyProperties(fmsCategoryPage, fmsCategory);
		fmsCategoryService.save(fmsCategory);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param fmsCategoryPage
	 * @return
	 */
	@AutoLog(value = "科目大类-编辑")
	@ApiOperation(value="科目大类-", notes="科目大类-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody FmsCategoryPage fmsCategoryPage) {
		FmsCategory fmsCategory = new FmsCategory();
		BeanUtils.copyProperties(fmsCategoryPage, fmsCategory);
		fmsCategoryService.updateById(fmsCategory);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "科目大类-通过id删除")
	@ApiOperation(value="科目大类-通过id删除", notes="科目大类-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
		fmsCategoryService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "科目大类-批量删除")
	@ApiOperation(value="科目大类-批量删除", notes="科目大类-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
	    this.fmsCategoryService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "科目大类-通过id查询")
	@ApiOperation(value="科目大类-通过id查询", notes="科目大类-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) Long id) {
		FmsCategory fmsCategory = fmsCategoryService.getById(id);
		return Result.ok(fmsCategory);
	}
	
	//===========================以下是子表信息操作相关API====================================
	
	/**
	 * 通过主表id查询科目小类
	 *
  	 * @param fmsCategorySub
	 * @return
	 */
	@AutoLog(value = "科目小类-通过主表id查询")
    @ApiOperation(value="科目小类-通过主表id查询", notes="科目小类-通过主表id查询")
	@GetMapping(value = "/listFmsCategorySubByMainId")
	public Result<?> listFmsCategorySubByMainId(FmsCategorySub fmsCategorySub,
                								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                								  HttpServletRequest req) {
        if(fmsCategorySub.getCategoryId()!=null) {
            QueryWrapper<FmsCategorySub> queryWrapper = QueryGenerator.initQueryWrapper(fmsCategorySub, req.getParameterMap());
            Page<FmsCategorySub> page = new Page<FmsCategorySub>(pageNo, pageSize);
            IPage<FmsCategorySub> pageList =  fmsCategorySubService.page(page, queryWrapper);
            return Result.ok(pageList);
        }else{
            return Result.error("请选择一条记录");
        }
    }

	 /**
	  * 通过主表id查询全部科目小类
	  *
	  * @param mainId
	  * @return
	  */
	 @GetMapping(value = "/queryFmsCategorySubByMainId")
	 public Result<?> queryFmsCategorySubByMainId(@RequestParam(name = "mainId", required = true) Long mainId) {
		 List<FmsCategorySub> fmsCategorySubList = fmsCategorySubService.selectByMainId(mainId);
		 return Result.ok(fmsCategorySubList);
	 }
	
	/**
     * 添加科目小类
     *
     * @param fmsCategorySub
     * @return
     */
    @AutoLog(value = "科目小类-添加")
    @ApiOperation(value="科目小类-添加", notes="科目小类-添加")
    @PostMapping(value = "/addFmsCategorySub")
    public Result<?> addFmsCategorySub(@RequestBody FmsCategorySub fmsCategorySub) {
        fmsCategorySubService.save(fmsCategorySub);
        return Result.ok("添加科目小类成功！");
    }
    
    /**
     * 编辑科目小类
     *
     * @param fmsCategorySub
     * @return
     */
    @AutoLog(value = "科目小类-编辑")
    @ApiOperation(value="科目小类-编辑", notes="科目小类-编辑")
    @PutMapping("/editFmsCategorySub")
    public Result<?> editFmsCategorySub(@RequestBody FmsCategorySub fmsCategorySub) {
        fmsCategorySubService.updateById(fmsCategorySub);
        return Result.ok("编辑科目小类成功！");
    }
    
    /**
     * 通过id删除科目小类
     *
     * @param id
     * @return
     */
    @AutoLog(value = "科目小类-通过id删除")
    @ApiOperation(value="科目小类-通过id删除", notes="科目小类-通过id删除")
    @DeleteMapping(value = "/deleteFmsCategorySub")
    public Result<?> deleteFmsCategorySub(@RequestParam(name = "id", required = true) Long id) {
       fmsCategorySubService.removeById(id);
        return Result.ok("删除科目小类成功！");
    }
	
	/**
     * 批量删除科目小类
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "科目小类-批量删除")
    @ApiOperation(value="科目小类-批量删除", notes="科目小类-批量删除")
    @DeleteMapping(value = "/deleteBatchFmsCategorySub")
    public Result<?> deleteBatchFmsCategorySub(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        } 
        this.fmsCategorySubService.removeByIds(Arrays.asList(ids.split(",")));
       	return Result.ok("批量删除成功！");

    }
    

    /**
    * 导出excel
    *
    * @param request
    * @param fmsCategory
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FmsCategory fmsCategory) {
      // Step.1 组装查询条件
      QueryWrapper<FmsCategory> queryWrapper = QueryGenerator.initQueryWrapper(fmsCategory, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<FmsCategoryPage> pageList = new ArrayList<FmsCategoryPage>();
      List<FmsCategory> fmsCategoryList = fmsCategoryService.list(queryWrapper);
      for (FmsCategory temp : fmsCategoryList) {
          FmsCategoryPage vo = new FmsCategoryPage();
          BeanUtils.copyProperties(temp, vo);
          List<FmsCategorySub> fmsCategorySubList = fmsCategorySubService.selectByMainId(temp.getId());
          vo.setFmsCategorySubList(fmsCategorySubList);
          pageList.add(vo);
      }
      //Step.3 调用AutoPoi导出Excel
      ModelAndView mv = new ModelAndView(new EntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "科目大类");
      mv.addObject(NormalExcelConstants.CLASS, FmsCategoryPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("科目大类数据", "导出人:"+sysUser.getRealname(), "科目大类"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<FmsCategoryPage> list = ExcelImportUtil.importExcel(file.getInputStream(), FmsCategoryPage.class, params);
              for (FmsCategoryPage page : list) {
                  FmsCategory po = new FmsCategory();
                  BeanUtils.copyProperties(page, po);
                  fmsCategoryService.saveMain(po, page.getFmsCategorySubList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }
}
